package _dp_base;

/**
 * 712. 两个字符串的最小ASCII删除和
 */
public class No712 {
    private String s1, s2;
    private int[][] cache;

    /**
     * 1. 递归
     */
    public int minimumDeleteSum1(String s1, String s2) {
        this.s1 = s1;
        this.s2 = s2;
        int n = s1.length();
        int m = s2.length();
        cache = new int[n][m];

        return dfs(n - 1, m - 1);
    }

    private int dfs(int i, int j) {
        if (i < 0 && j < 0) return 0;
        else if (i < 0) return dfs(i, j - 1) + s2.charAt(j);
        else if (j < 0) return dfs(i - 1, j) + s1.charAt(i);
        else if (cache[i][j] != 0) return cache[i][j];
        else if (s1.charAt(i) == s2.charAt(j)) return cache[i][j] = dfs(i - 1, j - 1);
        else return cache[i][j] = Math.min(dfs(i - 1, j) + s1.charAt(i), dfs(i, j - 1) + s2.charAt(j));
    }

    /**
     * 2. 迭代
     */
    public int minimumDeleteSum2(String s1, String s2) {
        int n = s1.length();
        int m = s2.length();

        int[][] f = new int[n + 1][m + 1];
        for (int j = 0; j < m; j++) {
            f[0][j + 1] = f[0][j] + s2.charAt(j);
        }
        for (int i = 0; i < n; i++) {
            f[i + 1][0] = f[i][0] + s1.charAt(i);
            for (int j = 0; j < m; j++) {
                if (s1.charAt(i) == s2.charAt(j)) f[i + 1][j + 1] = f[i][j];
                else f[i + 1][j + 1] = Math.min(f[i][j + 1] + s1.charAt(i), f[i + 1][j] + s2.charAt(j));
            }
        }

        return f[n][m];
    }

    /**
     * 4. 空间优化
     */
    public int minimumDeleteSum4(String s1, String s2) {
        int n = s1.length();
        int m = s2.length();

        int[] f = new int[m + 1];
        for (int j = 0; j < m; j++) {
            f[j + 1] = f[j] + s2.charAt(j);
        }
        for (int i = 0; i < n; i++) {
            int pre = f[0];
            f[0] = f[0] + s1.charAt(i);
            for (int j = 0; j < m; j++) {
                int temp = f[j + 1];
                if (s1.charAt(i) == s2.charAt(j)) f[j + 1] = pre;
                else f[j + 1] = Math.min(f[j + 1] + s1.charAt(i), f[j] + s2.charAt(j));
                pre = temp;
            }
        }

        return f[m];
    }
}
